package com.example.singleton.register;

import java.io.*;

/**
 * 枚举实现的单例模式
 */
public enum EnumSingleton implements Serializable {

    INSTANCE;

    private Object data;

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public EnumSingleton getInstance(){
        return INSTANCE;
    }

    //    public SingletonEnum getInstance() {
//        return INSTANCE;
//    }




    public static void main(String[] args) {

        try {
            // 枚举获取的单例对象
            EnumSingleton s1 = EnumSingleton.INSTANCE;
            System.out.println("枚举单例获取:"+s1);


            // 使用反射破坏枚举单例

//            Class<?> clazz = SingletonEnum.class;
//            Constructor con = clazz.getDeclaredConstructor();
//            con.setAccessible(true);
//            SingletonEnum s2 = (SingletonEnum) con.newInstance();
//
//            System.out.println("反射获取:"+s2);
//            System.out.println(s1 == s2);


            // 使用序列化破坏单例

//            // 将生成的对象进行序列化
//            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("SingletonEnum.txt"));
//            outputStream.writeObject(s1);
//            outputStream.flush();
//            outputStream.close();
//
//            // 将序列化的对象读取出来
//            ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("SingletonEnum.txt"));
//            SingletonEnum s3 = (SingletonEnum)inputStream.readObject();
//            inputStream.close();
//            System.out.println("序列化获取:"+s3);
//            System.out.println(s1 == s3);


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
